import { shallowRef } from 'vue'
import type { ResultData, ResultList } from '@/@types/index.type'
import { mergeObject } from '@/utils/tool'
import { useDialog, useMessage } from 'naive-ui'

interface QueryFn<T> {
  (data: any): Promise<ResultData<ResultList<T>>>
}

interface Option<T> {
  queryFn: QueryFn<T>
  startSearch?: boolean
  params?: Record<string, any>
  deleteFn?: (id: number) => Promise<ResultData<unknown>>
  beforeQuery?: () => void
}

/**
 *
 * @param option 配置项
 * @returns
 */
export function useCurd<T = any>(option: Option<T>) {
  // 默认配置
  const defaultOptions = {
    startSearch: true
  }

  const list = shallowRef<T[]>([]) // 数据列表
  const total = ref(0) // 总数
  const loading = ref(false) // 加载状态

  const pageNum = ref(1) // 页码
  const pageSize = ref(10) // 页大小

  // 参数
  const queryParams = ref(option.params || {})

  const dialog = useDialog()
  const message = useMessage()

  mergeObject(option, defaultOptions)

  // 查询
  async function query() {
    option?.beforeQuery && (await option.beforeQuery())
    if (!option.queryFn) return
    try {
      loading.value = true
      const res = await option.queryFn({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...queryParams.value
      })
      list.value = res.data.list
      total.value = res.data.total
      loading.value = false
    } catch (error) {
      loading.value = false
    }
  }

  async function handleDelete(id: number) {
    dialog.warning({
      title: '提示',
      content: '是否确定删除数据？',
      positiveText: '确认',
      negativeText: '取消',
      onPositiveClick: async () => {
        if (!option?.deleteFn) return
        await option.deleteFn(id)
        message.success('删除成功')
        query()
      }
    })
    // option.deleteFn && (await option.deleteFn(id))
  }

  onMounted(() => {
    option?.startSearch && query()
  })

  return { query, list, total, pageNum, pageSize, queryParams, loading, handleDelete }
}
